package comag

import (
	v1log "gitee.com/captials-team/ubdframe/src/pkg/logs"
	"math"
	"time"
)

type CtlRater struct {
	StopNotifyWorker

	Do   func()
	Rate int64

	v1log.InvokeLog

	ch chan int
}

func (ctl *CtlRater) Start() {
	defer ctl.Info("do by rate stopped")

	if ctl.ch == nil {
		ctl.ch = make(chan int, 64)
	}
	if ctl.Rate <= 0 {
		ctl.Rate = 1
	}

	go ctl.ctlRate()
	ctl.start()
}

func (ctl *CtlRater) start() {
	ctl.Info("ctl rate start work")
	do := ctl.Do
	for {
		select {
		case num, ok := <-ctl.ch:
			if !ok {
				return
			}
			if num <= 0 {
				continue
			}
			if do != nil {
				for i := 1; i <= num; i++ {
					do()
				}
			}
			ctl.Info("do success %d, func is %t", num, do != nil)
		case <-ctl.StopNotify():
			return
		}
	}
}

func (ctl *CtlRater) ctlRate() {
	interval := time.Millisecond * 100 //单次执行间隔

	ti := time.NewTicker(interval)
	add := float64(ctl.Rate) / float64(time.Second/interval) //每次间隔增加的值
	var x float64 = 0

	ctl.Debug("ctl rate will do every %s, every %.3f", interval, add)
	for {
		select {
		case <-ti.C:
			num := math.Floor(x + add)
			x = x + add - num
			ctl.ch <- int(num)
		case <-ctl.StopNotify():
			return
		}
	}
}
